package com.executor.gateway.filters.global;

import com.executor.gateway.core.util.BloomFilterUtils;
import com.executor.gateway.core.util.CommonUtils;
import com.executor.gateway.model.po.IpList;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Auther: miaoguoxin
 * @Date: 2019/4/28 0028 17:36
 * @Description: ip过滤器（基于Redis布隆过滤器实现）
 */
@Component
@Slf4j
public class IpListGlobalFilter implements GlobalFilter, Ordered {
    
    @Autowired
    private BloomFilterUtils bloomFilterService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String remoteIP = CommonUtils.getRemoteIP(request);
        if (remoteIP == null) {
            response.setStatusCode(HttpStatus.BAD_REQUEST);
            return response.setComplete();
        }

        // 检查是否在黑名单中
        boolean inBlacklist = bloomFilterService.mightContain(remoteIP, IpList.BLACK_TYPE);
        if (inBlacklist) {
            log.warn("IP {} is in blacklist, access denied", remoteIP);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        // 检查白名单（如果白名单存在，则只允许白名单中的IP访问）
        boolean whitelistExists = bloomFilterService.isWhitelistExists(IpList.WHITE_TYPE);
        if (whitelistExists) {
            boolean inWhitelist = bloomFilterService.mightContain(remoteIP, IpList.WHITE_TYPE);
            if (!inWhitelist) {
                log.warn("IP {} is not in whitelist, access denied", remoteIP);
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}